package com.tensquare.user.controller;

import cn.hutool.core.util.StrUtil;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;
import com.tensquare.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zzb
 * @create 2021/2/22
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    //发送手机验证码
    @PostMapping("sendsms/{mobile}")
    public Result sendValidCode(@PathVariable String mobile){
        userService.sendMessage(mobile);
        return new Result(true, StatusCode.OK,"发送消息成功");
    }

    //用户注册
    @PostMapping("register/{code}")
    public Result add(@RequestBody User user,@PathVariable String code){
        Boolean b = userService.add(user, code);
        if (b){
            return new Result(true,StatusCode.OK,"用户注册成功");
        }
        return new Result(false,StatusCode.ERROR,"注册失败");
    }

    //用户登录
    @PostMapping("login")
    public Result login(@RequestBody User user){
        //查询用户是否存在

            User loginuser = userService.findUser(user);
            if (loginuser != null){
                //创建token
                String token = jwtUtil.createJwt(user.getId(), user.getNickname(), "user");
                //放到map中
                Map map = new HashMap();
                map.put("name",user.getNickname());
                map.put("token",token);
                return new Result(true,StatusCode.OK,"登录成功",map);
            }

        return new Result(false,StatusCode.ERROR,"登录失败，不存在此用户");
    }

    //根据id删除用户
    @DeleteMapping("{userId}")
    public Result deleteById(@PathVariable String userId){
        //从请求作用域得到值
        Claims claims = (Claims) request.getAttribute("claims");
        //判断不为空并且是否是用户
        if (claims != null){
            if ("admin".equals(claims.get("role"))){
                userService.deleteById(userId);
                return new Result(true,StatusCode.OK,"删除用户成功");
            }
        }
        return new Result(false,StatusCode.ERROR,"无权访问");
    }
}
